package com.itheima.core;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 解析xml
 * @作者 itcast
 * @创建日期 2020/10/13 15:13
 **/
public class XmlBeanDefinitionReader {
    private final DefaultListableBeanFactory beanFactory;

    public XmlBeanDefinitionReader(DefaultListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public void loadBeanDefinitions(String config){
        // 得到类加载器
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream in = classLoader.getResourceAsStream(config);
        // 1. 解析xml配置文件  Document
        SAXReader reader = new SAXReader();
        Document document;
        try {
             document = reader.read(in);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("配置文件格式错误");
        }
        Element rootElement = document.getRootElement();
        List<Element> beanEles = rootElement.elements("bean");
        for (Element beanEle : beanEles) {
            // 2. 找到所有的bean标签,   将每一个bean标签封装成 BeanDefinition对象
            BeanDefinition beanDefinition = parseBeanDefinition(beanEle);
            // 3. 将beanDefinition对象存入 beanDacotry的map集合中
            beanFactory.registryBeanDefinition(beanDefinition);
        }
    }

    private BeanDefinition parseBeanDefinition(Element beanEle){
        BeanDefinition beanDefinition = new BeanDefinition();
        // beanDefinition封装
        String beanName = beanEle.attributeValue("id");
        String className = beanEle.attributeValue("class");
        String scope = beanEle.attributeValue("scope");
        beanDefinition.setBeanName(beanName);
        beanDefinition.setClassName(className);
        if(scope!=null && !"".equals(scope)){
            beanDefinition.setScope(scope);
        }

        // 获取bean标签下的 所有 property标签
        List<Element> propertyEles = beanEle.elements("property");
        for (Element propertyEle : propertyEles) {
            Property property = new Property();
            property.setName(propertyEle.attributeValue("name"));
            property.setValue(propertyEle.attributeValue("value"));
            property.setRef(propertyEle.attributeValue("ref"));

            beanDefinition.getPropertiyList().add(property);
        }
        return beanDefinition;
    }




}
